const fs = require('fs');
const session = require('express-session');
const express = require('express');
const app = express();
app.listen(3000, () => console.log('serve is running'));

//配置中间件
app.use(session({
    secret: 'jisnffn',
    saveUninitialized: true,
    resave: true
}));

app.get('/index.html', (req, res) => {
    fs.readFile('./public-files/index.html', 'utf-8', (err, data) => {
        if (req.session.abc != 'efg') {
            res.send('<script>alert("请先登录");location.href="/login.html";</script>');
            return;
        }
        let title = '白驹过隙';
        let author = '青青';
        let content = '欢迎您' +req.session.username;
        data = data.replace('{{title}}', title);
        data = data.replace('{{author}}', author);
        data = data.replace('{{content}}', content);
        res.send(data);
    });
});

//显示登录页面
app.get('/login.html', (req, res) => {
    fs.readFile('./public-files//login.html', 'utf-8', (err, data) => {
        res.send(data);
    })
});

//完成登录接口
app.use(express.urlencoded({ extended: false }));
app.post('/api/login', (req, res) => {
    if (req.body.username == 'admin' && req.body.password == '123') {
        req.session.abc = 'efg';
        req.session
        .username = '阿哲';
        res.send({ status: 200, msg: '登陆成功' })
    } else {
        res.send({ status: 500, msg: '登陆失败' })
    }
})